﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace ExcelJsonParser
{
    class JsonViewWorkBook : JsonWorkBookBase
    {
        JsonViewWorkSheets _jsonViewWorkSheets;
        public JsonViewWorkBook(Workbook wb): base(wb)
        {
            _jsonViewWorkSheets = new JsonViewWorkSheets();
            _workbook.Windows[1].Visible = false;
            _workbook.Windows[1].Caption = "test";
        }

        public Worksheet AddEmptySheet()
        {
            return _workbook.Sheets.Add();
        }
        public void ParseJsonCell(Range jsonSource)
        {
            _jsonViewWorkSheets.InitJsonView(jsonSource);
        }


        protected override void Init(Workbook wb)
        {
            _workbook.BeforeClose += new WorkbookEvents_BeforeCloseEventHandler(_workbook_BeforeClose);
        }

        void _workbook_BeforeClose(ref bool Cancel)
        {
            _workbook.Saved = true;
            if (_workbook.Application.Workbooks.Count > 1)
            {
                Cancel = true;
                _workbook.Windows[1].Visible = CloseJsonWorkBook();
            }
        }

        private Boolean CloseJsonWorkBook()
        {
            Boolean jsonWorkBookVisiable = true;
            Worksheet ws = _workbook.ActiveSheet;
            object javaObject = JsonWorkSheetTable.GetOutputJson(ws);
            JsonViewWorkSheet jsonVWs = null;
            _jsonViewWorkSheets.TryGetByWorksheet(ws, out jsonVWs);
            JsonWorkCell.SetCellByJson(jsonVWs.JsonSource,javaObject);
            jsonVWs.JsonSource.Parent.Visible = XlSheetVisibility.xlSheetVisible;
            try
            {
                ws.Visible = XlSheetVisibility.xlSheetVeryHidden;
            }
            catch (Exception)
            {
                jsonWorkBookVisiable = false;
            }
            return jsonWorkBookVisiable;
        }
    }
}
